﻿using IntelligentAgriculture.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentAgriculture.Domain.Impl
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly AgricultureDbContext _db;
        public BaseRepository(AgricultureDbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>返回受影响的行数</returns>
        public int Add(T entity)
        {
            _db.Set<T>().Add(entity);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">要删除的实体</param>
        /// <returns>受影响的行数</returns>
        public int Delete(T entity)
        {
            _db.Set<T>().Remove(entity);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entities">要删除的实体集合</param>
        /// <returns>返回受影响的行数</returns>
        public int DeleteRange(List<T> entities)
        {
            _db.Set<T>().RemoveRange(entities);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T Get(int id)
        {
            return _db.Set<T>().Find(id);
        }
        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns>返回所有数据</returns>
        public IQueryable<T> GetQuery()
        {
            var list = _db.Set<T>().AsQueryable();
            return list;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">要修改的实体</param>
        /// <returns>返回受影响的行数</returns>
        public int Update(T entity)
        {
            _db.Set<T>().Update(entity);
            return _db.SaveChanges();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entities">要修改的实体集合</param>
        /// <returns>返回受影响的行数</returns>
        public int UpdateRange(List<T> entities)
        {
            _db.Set<T>().UpdateRange(entities);
            return _db.SaveChanges();
        }
    }
}
